﻿/*
 ASP.NET MvcPager 分页组件
 Copyright:2009-2011 陕西省延安市吴起县 杨涛\Webdiyer (http://www.webdiyer.com)
 Source code released under Ms-PL license
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace OnlineMealOrdering.Extends.MvcPager
{
    public interface IPagedList
    {
        int CurrentPageIndex { get; set; }
        int PageSize { get; set; }
        int TotalItemCount { get; set; }
    }

    public class PagedList<T> : List<T>, IPagedList
    {
       
        public PagedList(IList<T> items, int pageIndex, int pageSize)
        {
            PageSize = pageSize;
            TotalItemCount = items.Count;
            CurrentPageIndex = pageIndex;
            for (int i = StartRecordIndex - 1; i < EndRecordIndex; i++)
            {
                Add(items[i]);
            }
        }

        public PagedList(IEnumerable<T> items, int pageIndex, int pageSize, int totalItemCount)
        {
            AddRange(items);
            TotalItemCount = totalItemCount;
            CurrentPageIndex = pageIndex;
            PageSize = pageSize;
        }

        public static PagedList<T> GeneratePagedList(IQueryable<T> allItems, int pageIndex, int pageSize)
        {
            if (pageIndex < 1)
                pageIndex = 1;
            var itemIndex = (pageIndex - 1) * pageSize;
            var pageOfItems = allItems.Skip(itemIndex).Take(pageSize);
            var count = allItems.Count();
            return new PagedList<T>(pageOfItems, pageIndex, pageSize, count);
        }

        public static PagedList<TModel> GeneratePagedList<TModel>(IQueryable<T> allItems, int pageIndex, int pageSize, Func<T, TModel> entityToModel)
        {
            var listEntity = GeneratePagedList(allItems, pageIndex, pageSize);
            var listModel = new List<TModel>();

            listEntity.ForEach(a => listModel.Add(entityToModel(a)));
            return new PagedList<TModel>(listModel, pageIndex, pageSize, allItems.Count());
        }

        public int CurrentPageIndex { get; set; }
        public int PageSize { get; set; }
        public int TotalItemCount { get; set; }
        public int TotalPageCount { get { return (int)Math.Ceiling(TotalItemCount / (double)PageSize); } }
        public int StartRecordIndex
        {
            get { return (CurrentPageIndex - 1) * PageSize + 1; }
        }
        public int EndRecordIndex
        {
            get
            {
                return TotalItemCount > CurrentPageIndex * PageSize ? CurrentPageIndex * PageSize : TotalItemCount;
            }
        }
    }
}
